import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';
import 'package:aliyun_log_dart_sdk/aliyun_log_dart_sdk.dart';

/*
阿里云产品工具类 androi/iOS
日志: https://pub-web.flutter-io.cn/packages/aliyun_log_dart_sdk/install

注意: 由于gradle8+需要定义namespace,此^1.1.1版本没有定义则编译报错,因此在开发项目的dependencies中在依赖使用

dependencies:
  aliyun_log_dart_sdk: ^1.1.1

import 'package:aliyun_log_flutter_sdk/aliyun_log_flutter_sdk.dart';


 */
abstract class XAliyunLogUtils{

  static AliyunLogDartSdk? _aliyunLogSdk;

  //1.初始化
  static void init(
      {
        required String appName,//自定义,用于标记
        required String endpoint,
        required String project,
        required String logstore,
        required String accessKeyID,
        required String accessKeySecret,
        Map<String,dynamic>? customTags,
      }
      ) async{

    if(!XFlutterUtils.isAndroidOriOSSystem()){
      XLogUtils.printLog('---非 Android/iOS 平台,不支持阿里云日志!');
      return;
    }

    if(_aliyunLogSdk==null){

      // endpoint、project、logstore 后续可动态更新
      LogProducerConfiguration configuration = LogProducerConfiguration(
          endpoint: endpoint,
          project: project,
          logstore: logstore
      );

      configuration.accessKeyId = accessKeyID;
      configuration.accessKeySecret = accessKeySecret;
      //configuration.securityToken = 'your access key token'; // 使用 STS 方式获取的 AK 时需要

      configuration.persistent = true; // 开启断点续传
      configuration.persistentFilePath = 'flutter/demo'; // binlog 缓存目录
      configuration.persistentForceFlush = false; // 关闭强制刷新，建议关闭，开启后会对性能产生一定的影响
      configuration.persistentMaxFileCount = 10; // 缓存文件数量，默认为 10
      configuration.persistentMaxFileSize = 1024 * 1024; // 单个缓存文件的大小，默认为 1MB
      configuration.persistentMaxLogCount = 64 * 1024; // 缓存日志的数量，默认为 64K

      _aliyunLogSdk = AliyunLogDartSdk();
      LogProducerResult result = await _aliyunLogSdk!.initProducer(configuration);

      // add tag if you need
      if(customTags==null){
        await _aliyunLogSdk!.addTag('appName',appName);
        await _aliyunLogSdk!.addTag('code','Flutter');
        await _aliyunLogSdk!.addTag('systemName', XFlutterUtils.getSystemName());
      }else{

        await _aliyunLogSdk!.addTag('appName',appName);
        await _aliyunLogSdk!.addTag('code','Flutter');
        await _aliyunLogSdk!.addTag('systemName', XFlutterUtils.getSystemName());

        customTags.forEach((key, value) async {
          await _aliyunLogSdk!.addTag(key, '$value');
        });
      }
    }

  }

  //2.发送日志
  static void sendLog(
      String title,
      String msg,
  {
    String? otherInfo
  }
      )async{

    if(!XFlutterUtils.isAndroidOriOSSystem()){
      return;
    }

    // LogProducerResult code = await _aliyunLogSdk!.addLog({
    //   title: msg,
    //   'otherInfo': '$otherInfo',
    // });
    _aliyunLogSdk?.addLog({
      title: msg,
      'otherInfo': '$otherInfo',
    });

  }

}
